/**
 * Created by TamTT on 1/13/14.
 * FPT University - Da Nang
 * Capstone project - group 3
 * Jornee
 */
module.exports.controller = function(app, jwt, secret, db, authentication, util, async, log, colors){
	var mongojs = require('mongojs');
	var Wiki = require("wikijs");

	/**
	 * Get all host of a location - TamTT
	 */
	app.post('/all_hosts', function(req, res){
		authentication(req, function(result){
			if(result.loginStatus == 'error'){
				res.send({
					authen_status: 'error'
				});
			} else if(result.loginStatus == 'false'){
				res.send({
					authen_status: 'fail'
				});
			} else if(result.loginStatus == 'true'){
				/**
				 * Code begin
				 */
				var my_id = result.login_user;
				var country = (req.body.country || '').fromVi();
				var administrative_area_level_1 = (req.body.administrative_area_level_1 || '').fromVi();
				var locality = (req.body.locality || '').fromVi();
				var page = req.body.page;

				//Make query
				if(locality != administrative_area_level_1){
					if(locality == ''){
						var exact_place_query = {
							"country": country,
							"administrative_area_level1": administrative_area_level_1,
							"route": ''
						};
					} else {
						var exact_place_query = {
							"country": country,
							"locality": locality,
							"route": ''
						};
					}
				} else {
					if(locality == '' && administrative_area_level_1 == ''){
						var exact_place_query = {
							"country": country,
							"administrative_area_level1": administrative_area_level_1,
							"locality": locality,
							"route": ''
						};
					} else {
						var exact_place_query = {
							"country": country,
							"administrative_area_level1": administrative_area_level_1,
							"route": ''
						};
					}
				}
				log.info('All host - User %s - Search host in %s'.blue, my_id, util.inspect(exact_place_query));
				//Get place
				db.place.findOne(exact_place_query, function(err, place){
					if(err){
						log.error('All host - User %s - Error with %s'.yellow, my_id, err);
						res.send({
							authen_status: 'ok',
							status: 'error'
						});
					} else if(!place){
						log.warning('All host - User %s - No place'.yellow, my_id);
						res.send({
							authen_status: 'ok',
							status: 'fail'
						});
					} else {
						//Get host that register in the place
						log.warning('All host - User %s - Place Id %s'.yellow, my_id, place._id);
						db.host.find({
							place_id: place._id
						}, {
							_id: 0,
							user_id: 1,
							status: 1
						}, function(err, hosts){
							if(err){
								log.error('All host - User %s - Error with %s'.yellow, my_id, err);
								res.send({
									authen_status: 'ok',
									status: 'error'
								});
							} else {
								log.warning('All host - User %s - Num of host: %s'.yellow, my_id, hosts.length);
								var return_hosts = [];
								async.forEach(hosts, function(host, callback){
									var return_host = {};
									return_host.status = host.status;
									return_host.username = host.user_id;
									if(place.locality != ''){
										return_host.regis_location = place.locality + ', ' + place.administrative_area_level1 + ', ' + place.country;
									} else if(place.locality == '' && place.administrative_area_level1 != ''){
										return_host.regis_location = place.administrative_area_level1 + ', ' + place.country;
									} else if(place.locality == '' && place.administrative_area_level1 == '' && place.country != ''){
										return_host.regis_location = place.country;
									} else {
										return_host.regis_location = '';
									}
									//Get avatar of host
									db.users.findOne({
										username: host.user_id
									}, {
										_id: 0,
										avatar: 1
									}, function(err, user){
										if(err){
											log.error('All host - User %s - Error with %s'.red, my_id, err);
											res.send({
												authen_status: 'ok',
												status: 'fail'
											});
										}
										if(!user){
											return_host.avatar = '0.jpg';
										} else {
											return_host.avatar = user.avatar;
										}
										return_hosts.push(return_host);
										callback();
									});
								}, function(err){
									if(err){
										log.error('All host - User %s - Error with %s'.red, my_id, err);
										res.send({
											authen_status: 'ok',
											status: 'error'
										});
									} else {
										log.info('All host - User %s - Return: %s'.blue, my_id, util.inspect(return_hosts.length));
										res.send({
											authen_status: 'ok',
											status: 'ok',
											exact_hosts: return_hosts
										});
									}
								})
							}
						});
					}
				});
			}
		});
	});

	/**
	 * Get all questions - TamTT
	 */
	app.post('/all_questions', function(req, res){
		authentication(req, function(result){
			if(result.loginStatus == 'error'){
				res.send({
					authen_status: 'error'
				});
			} else if(result.loginStatus == 'false'){
				res.send({
					authen_status: 'fail'
				});
			} else if(result.loginStatus == 'true'){
				/**
				 * Code begin
				 */
				db.tipsquestion.find({}, function(err, questions){
					if(err){
						log.error('All questions - User %s - Error with %s'.red, result.login_user, err);
						res.send({
							authen_status: 'ok',
							status: 'error'
						});
					} else if(questions.length < 1){
						res.send({
							authen_status: 'ok',
							status: 'fail'
						});
					} else {
						log.info('All questions - User %s - OK'.blue, result.login_user);
						res.send({
							authen_status: 'ok',
							status: 'ok',
							questions: questions
						});
					}
				});
			}
		});
	});

	/**
	 * Get all tips of a question about a location - TamTT
	 */
	app.post('/all_tips', function(req, res){
		authentication(req, function(result){
			if(result.loginStatus == 'error'){
				res.send({
					authen_status: 'error'
				});
			} else if(result.loginStatus == 'false'){
				res.send({
					authen_status: 'fail'
				});
			} else if(result.loginStatus == 'true'){
				/**
				 * Code begin
				 */
				//Username: result.login_user
				var country = (req.body.country || '').fromVi();
				var administrative_area_level_1 = (req.body.administrative_area_level_1 || '').fromVi();
				var locality = (req.body.locality || '').fromVi();
				var page = req.body.page;
				var question_id = req.body.question_id;

				//Make query
				if(locality != administrative_area_level_1){
					if(locality == ''){
						var exact_place_query = {
							"country": country,
							"administrative_area_level1": administrative_area_level_1,
							"route": ''
						};
					} else {
						var exact_place_query = {
							"country": country,
							"locality": locality,
							"route": ''
						};
					}
				} else {
					if(locality == '' && administrative_area_level_1 == ''){
						var exact_place_query = {
							"country": country,
							"administrative_area_level1": administrative_area_level_1,
							"locality": locality,
							"route": ''
						};
					} else {
						var exact_place_query = {
							"country": country,
							"administrative_area_level1": administrative_area_level_1,
							"route": ''
						};
					}
				}
				log.info('All tips - User %s - Tips for question %s: %s'.blue, result.login_user, question_id, util.inspect(exact_place_query));
				//Get place
				db.place.findOne(exact_place_query, function(err, place){
					if(err){
						log.error('All tips - User %s - Error with %s'.red, result.login_user, err);
						res.send({
							authen_status: 'ok',
							status: 'error'
						});
					} else if(!place){
						log.warning('All tips - User %s - No place'.red, result.login_user);
						res.send({
							authen_status: 'ok',
							status: 'fail'
						});
					} else {
						//Get content of question by its id
						db.tipsquestion.findOne({
							_id: mongojs.ObjectId(question_id)
						}, function(err, question){
							if(err){
								log.error('All tips - User %s - Error with %s'.red, result.login_user, err);
								res.send({
									authen_status: 'ok',
									status: 'error'
								});
							} else if(!question){
								log.warning('All tips - User %s - No question'.red, result.login_user);
								res.send({
									authen_status: 'ok',
									status: 'fail'
								});
							} else {
								//Get host that register in the place
								db.host.aggregate({
									$match: {
										place_id: place._id
									}
								}, {
									$unwind: "$tips"
								}, {
									$match: {
										'tips.question': question.content
									}
								}, {
									$project: {
										_id: 0,
										user_id: 1,
										'tips.answer': 1
									}
								}, function(err, hosts){
									if(err){
										log.error('All tips - User %s - Error with %s'.red, result.login_user, err);
										res.send({
											authen_status: 'ok',
											status: 'error'
										});
									}
									var return_tips = [];
									var host_ids = [];
									hosts.forEach(function(host){
										host_ids.push(host.user_id);
									});
									db.users.find({
										username: {
											$in: host_ids
										}
									}, {
										_id: 0,
										username: 1,
										avatar: 1
									}, function(err, users){
										if(err){
											log.error('All tips - User %s - Error with %s'.red, result.login_user, err);
											res.send({
												authen_status: 'ok',
												status: 'error'
											});
										}
										var user_ids = [];
										users.forEach(function(user){
											user_ids.push(user.username);
										});
										hosts.forEach(function(host){
											if(host.tips.answer != ''){
												var return_tip = {};
												return_tip.user_id = host.user_id;
												return_tip.tip = host.tips.answer;
												return_tip.avatar = users[user_ids.indexOf(host.user_id)].avatar;
												return_tips.push(return_tip);
											}
										});
										log.info('All tips - User %s - Ok'.blue, result.login_user);
										res.send({
											authen_status: 'ok',
											status: 'ok',
											hosts: return_tips
										});
									});
								});
							}
						})
					}
				});
			}
		});
	});

	/**
	 * Get list of information of a place - TamTT
	 */
	app.post('/place_information_list', function(req, res){
		authentication(req, function(result){
			if(result.loginStatus == 'error'){
				res.send({
					authen_status: 'error'
				});
			} else if(result.loginStatus == 'false'){
				res.send({
					authen_status: 'fail'
				});
			} else if(result.loginStatus == 'true'){
				/**
				 * Code begin
				 */
				//Username: result.login_user
				var language = req.body.language || 'en';
				var country = (req.body.country || '').fromVi();
				var administrative_area_level_1 = (req.body.administrative_area_level_1 || '').fromVi();
				var locality = (req.body.locality || '').fromVi();
				var page = req.body.page;

				//Make query
				if(locality != ''){
					var exact_place_query = locality;
				} else if(locality == '' && administrative_area_level_1 != ''){
					var exact_place_query = administrative_area_level_1;
				} else if(locality == '' && administrative_area_level_1 == '' && country != ''){
					var exact_place_query = country
				}

				Wiki.search(exact_place_query, 50, language, function(err, results){
					if(err){
						log.error('List place\'s information - User %s - Error with %s'.red, result.login_user, err);
						res.send({
							authen_status: 'ok',
							status: 'error'
						});
					} else {
						log.info('List place\'s information - User %s - Ok'.blue, result.login_user);
						res.send({
							authen_status: 'ok',
							status: 'ok',
							results: results
						});
					}
				});
			}
		});
	});

	/**
	 * Get wiki information
	 */
	app.post('/place_information', function(req, res){
		authentication(req, function(result){
			if(result.loginStatus == 'error'){
				res.send({
					authen_status: 'error'
				});
			} else if(result.loginStatus == 'false'){
				res.send({
					authen_status: 'fail'
				});
			} else if(result.loginStatus == 'true'){
				/**
				 * Code begin
				 */
				//Username: result.login_user
				var my_id = result.login_user;
				var page_name = req.body.page_name || '';
				var language = req.body.language || 'en';
				log.info('Place information - User %s - Received: %s %s'.blue, my_id, page_name, language);

				var content_return = {};
				Wiki.page(page_name, language, function(err, page){
					content_return.original_link = page.url;
					log.info('Place information - User %s - Get page Ok'.blue, my_id);
					page.summary(language, function(err, summary){
						if(err){
							log.error('Place information - User %s - Error in: Summary - %s'.blue, my_id, err);
							res.send({
								authen_status: 'ok',
								status: 'error'
							});
						} else {
							log.info('Place information - User %s - Get summary Ok'.blue, my_id);
							content_return.summary = summary;
							page.content(language, function(err, content){
								if(err){
									log.error('Place information - User %s - Error in: Content - %s'.blue, my_id, err);
									res.send({
										authen_status: 'ok',
										status: 'error'
									});
								} else {
									log.info('Place information - User %s - Get content Ok'.blue, my_id);
									content_return.content = content;
									page.images(language, function(err, images){
										if(err){
											log.error('Place information - User %s - Error in: Image - %s'.blue, my_id, err);
											res.send({
												authen_status: 'ok',
												status: 'error'
											});
										} else {
											log.info('Place information - User %s - Get images Ok'.blue, my_id);
											content_return.images = [];
											for(var i = 0; i < images.length; i++){
												if(images[i] != null && images[i].slice(-3) != 'svg'){
													content_return.images.push(images[i]);
												}
											}
											log.info('Place information - User %s - Ok'.blue, my_id);
											res.send({
												authen_status: 'ok',
												status: 'ok',
												results: content_return
											});
										}
									});
								}
							});
						}
					});

				});
			}
		});
	});

	/**
	 * Get list of information of a place - TamTT
	 */
	app.post('/interesting_places', function(req, res){
		authentication(req, function(result){
			if(result.loginStatus == 'error'){
				res.send({
					authen_status: 'error'
				});
			} else if(result.loginStatus == 'false'){
				res.send({
					authen_status: 'fail'
				});
			} else if(result.loginStatus == 'true'){
				/**
				 * Code begin
				 */
				//Username: result.loginUser
				var country = (req.body.country || '').fromVi();
				var administrative_area_level_1 = (req.body.administrative_area_level_1 || '').fromVi();
				var locality = (req.body.locality || '').fromVi();
				var page = req.body.page;

				//Make query
				if(locality != administrative_area_level_1){
					if(locality == ''){
						var exact_place_query = {
							"country": country,
							"administrative_area_level1": administrative_area_level_1
						};
					} else {
						var exact_place_query = {
							"country": country,
							"locality": locality
						};
					}
				} else {
					if(locality == ''){
						var exact_place_query = {
							"country": country
						};
					} else {
						var exact_place_query = {
							"country": country,
							"administrative_area_level1": administrative_area_level_1
						};
					}
				}
				log.info('View iplace - User %s - Place query: %s'.blue, result.login_user, util.inspect(exact_place_query));
				//Find places in user's request
				db.place.find(exact_place_query, {
					_id: 1
				}, function(err, places){
					if(err){
						log.error('View iplace - User %s - Error with %s'.red, result.login_user, err);
						res.send({
							authen_status: 'ok',
							status: 'error'
						});
					}
					log.info('View iplace - User %s - Places: %s'.blue, result.login_user, util.inspect(places));
					var result_places = [];
					places.forEach(function(place){
						result_places.push(place._id);
					});
					//Find all interesting place that exist in places
					db.interestingplace.find({
						place_id: {
							$in: result_places
						}
					}, {
						_id: 1,
						iplace_name: 1,
						place_id: 1,
						category: 1
					}, function(err, iplaces){
						if(err){
							log.error('View iplace - User %s - Error with %s'.red, result.login_user, err);
							res.send({
								authen_status: 'ok',
								status: 'error'
							});
						} else {
							log.info('View iplace - User %s - iPlaces: %s'.blue, result.login_user, util.inspect(iplaces));
							var return_iplaces = [];
							async.each(iplaces, function(iplace, callback){
								db.entry.find({
									iplace_id: iplace._id
								}, {
									_id: 0,
									coordinate: 1,
									path: 1,
									iplace_name: 1
								}, function(err, entries){
									if(err){
										log.error('View iplace - User %s - Error with %s'.red, result.login_user, err);
										res.send({
											authen_status: 'ok',
											status: 'error'
										});
									}
									log.info('View iplace - User %s - Entries: %s'.blue, result.login_user, util.inspect(entries));
									if(entries.length > 0){
										var return_iplace = {};
										return_iplace.coordinate = entries[0].coordinate;
										return_iplace.list_entries = [];
										entries.forEach(function(entry){
											return_iplace.list_entries.push({
												path: entry.path,
												iplace_name: entry.iplace_name || ""
											});
										});
										return_iplace.category = iplace.category;
										return_iplaces.push(return_iplace);
										callback();
									} else {
										callback();
									}
								});
							}, function(err){
								if(err){
									log.error('View iplace - User %s - Error with %s'.red, result.login_user, err);
									res.send({
										authen_status: 'ok',
										status: 'error'
									});
								}
								log.info('View iplace - User %s - Places:: %s'.blue, result.login_user, util.inspect(return_iplaces.length));
								res.send({
									authen_status: 'ok',
									status: 'ok',
									places: return_iplaces
								});
							});
						}
					});
				});
			}
		});
	});
};